package database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import jsonbean.Qualitys;

/**
 * Created by Lxh on 2018/1/2.
 */

public class LivesqliteUtil {
    private static SQLiteDatabase dbw;
    private static SQLiteDatabase dbr;
    static LivesqliteHelper livesqliteHelper = null;

    public LivesqliteUtil(Context context) {
        livesqliteHelper = new LivesqliteHelper(context);
        dbr = livesqliteHelper.getReadableDatabase();
        dbw = livesqliteHelper.getWritableDatabase();
    }

    public void InsertData(List<Qualitys> list) {
        long resultNumber = 0;
        for (Qualitys qualitys : list) {
            ContentValues values = new ContentValues();
            values.put("co", qualitys.getCo2());
            values.put("light", qualitys.getLight());
            values.put("pm", qualitys.getPm());
            values.put("humidity", qualitys.getHumidity());
            values.put("temp", qualitys.getTemp());
            resultNumber = dbw.insert("qualitys", null, values);
        }
        if (resultNumber != 0) {
            dbw.close();
            Log.w("Lxh", "影响的行数： " + resultNumber);
        }
    }

    public List<Qualitys> QueryData() {
        String sql = "select * from qualitys order by id desc limit 0,20";
        List<Qualitys> list = new ArrayList<>();
        Qualitys qualitys = null;
        Cursor cursor = dbr.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            qualitys = new Qualitys();
            qualitys.setCo2(cursor.getInt(cursor.getColumnIndex("co")));
            qualitys.setLight(cursor.getInt(cursor.getColumnIndex("light")));
            qualitys.setPm(cursor.getInt(cursor.getColumnIndex("pm")));
            qualitys.setHumidity(cursor.getInt(cursor.getColumnIndex("humidity")));
            qualitys.setTemp(cursor.getInt(cursor.getColumnIndex("temp")));
            list.add(qualitys);
        }
        Log.w("Lxh", "QueryData:查询到的数据量为  " + list.size());
        dbr.close();
        return list;
    }
}
